//
//  NSString+Timestamp.m
//  HSCategoryKit
//
//  Created by huang on 2018/8/1.
//

#import "NSString+Timestamp.h"

@implementation NSString (Timestamp)

#pragma mark 获取当前时间戳
+ (NSString*)timeString
{
    return [NSString stringWithFormat:@"%.0f",[[NSDate date] timeIntervalSince1970]*1000];
}

+ (NSString *)currentTime
{
    NSDate *currentDate = [NSDate date];
    NSString *date = [NSString stringWithFormat:@"%f",[currentDate timeIntervalSince1970]];
    return date;
}

#pragma mark 获取当前时间
+ (NSString *)currentDateStr
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
    return dateString;
}

#pragma mark 时间戳转为对应的时间
+ (NSString *)timeStringFromTimestampStr:(NSString *)timestampStr
{
    return [NSString timeStringFromTimestamp:[timestampStr doubleValue]/1000.0];
}

+ (NSString *)timeStringFromTimestamp:(NSTimeInterval)timestamp
{
    NSString *_timestamp;
    time_t now;
    time(&now);
    
    int distance = (int)difftime(now, timestamp);
    if (distance < 0) distance = 0;
    
    if (distance < 10) {
        _timestamp = [NSString stringWithFormat:@"刚刚"];
    } else if (distance < 60) {
        _timestamp = [NSString stringWithFormat:@"%d%@", distance, @"秒前"];
    } else if (distance < 60 * 60) {
        distance = distance / 60;
        _timestamp = [NSString stringWithFormat:@"%d%@", distance, @"分钟前"];
    } else {
        static NSDateFormatter *dateFormatter = nil;
        if (dateFormatter == nil) {
            dateFormatter = [[NSDateFormatter alloc] init];
        }
        
        NSDate *now = [NSDate date];
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
        [dateFormatter setDateFormat:@"YY"];
        NSString * timestampYear = [dateFormatter stringFromDate:date];
        NSString * timestampYearNow = [dateFormatter stringFromDate:now];
        if ([timestampYear isEqualToString:timestampYearNow]) {
            [dateFormatter setDateFormat:@"dd"];
            NSString * timestampDay = [dateFormatter stringFromDate:date];
            NSString * timestampDayNow = [dateFormatter stringFromDate:now];
            if ([timestampDay isEqualToString:timestampDayNow]) {
                // 同一天内
                [dateFormatter setDateFormat:@"HH:mm"];
            } else {
                [dateFormatter setDateFormat:@"M月dd日"];
            }
        } else {
            // 跨年了
            [dateFormatter setDateFormat:@"YY.MM.dd"];
        }
        _timestamp = [dateFormatter stringFromDate:date];
    }
    return _timestamp;
}

@end
